/**********************************************************************
 * 查找终端客户 通过经销商客户的客户编码 和 终端客户信息去查找对应的终端
 *
 * @url: /services/apexrest/rest
 * @data:
 *  {
        data:{
			dealer:1234,经销商客户编码
			terminal:1234,终端客户名称

        }
    }
*************************************************************************/
@RestResource(urlMapping='/CRM/queryAccountForOrder')
global with sharing class QueryAccountForOrder {
    @HttpPost
    global static RestReturnMessage doPost(Map<String,String> data) {

    	try {

    		if(		data == null 
    			|| data.isEmpty() 
    			|| !data.containsKey('dealer') 
    			|| !data.containsKey('terminal'))throw new DmlException('参数异常!');

    		String terminal = '%'+data.get('terminal')+'%';
    		//从经销商的终端客户中去找 对应的终端客户
    		List<Map<String,String>> datas = new List<Map<String,String>>();
    		for (MajorUserInfo__c m : [select MajorCustomer__c ,MajorCustomer__r.Name ,MajorCustomer__r.AccountNumber 
    			from MajorUserInfo__c where Dealer__r.AccountNumber =:data.get('dealer') and MajorCustomer__r.Name like:terminal ]) {
    			
    			datas.add(transData(m));
    		}

    		if(!datas.isEmpty())return Utils.getRestReturnMessage(true, 'success', datas);

    		for (Account acc  :[select Id ,Name ,AccountNumber from Account where Name like: terminal limit 100 ] ) {
    			
    			datas.add(transData(acc));
    		}
    		return Utils.getRestReturnMessage(true, 'success', datas);
    	    
    	}catch (Exception e) {
    	    return Utils.getRestReturnMessage(false, e.getMessage(),  new List<Map<String,String>>() );

    	}
    	

    }

    private static Map<String,String> transData(MajorUserInfo__c mu ){
    	
    	Map<String,String>  m = new Map<String,String> ();
    	m.put('Id',mu.MajorCustomer__c);
    	m.put('Name',mu.MajorCustomer__r.Name);
    	m.put('AccountNumber',mu.MajorCustomer__r.AccountNumber);

    	m.put('Belong','true' );
    	return m;

    }
    private static Map<String,String> transData(Account mu ){
    	
    	Map<String,String>  m = new Map<String,String> ();
    	m.put('Id',mu.Id);
    	m.put('Name',mu.Name);
    	m.put('AccountNumber',mu.AccountNumber);

    	m.put('Belong','false' );
    	return m;

    }



}